﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using NLog;

namespace DeleteEmptyFolders
{
	public static class FolderDeleter
	{
		private static Logger logger = LogManager.GetCurrentClassLogger();

		public static IEnumerable<string> GetDirsToDelete(string ignoreFilesList, string baseDir)
		{
			string[] ignoreFiles = getIgnoreFiles(ignoreFilesList);
			return GetDirsToDelete(ignoreFiles, baseDir);
		}

		public static IEnumerable<string> GetDirsToDelete(string[] ignoreFiles, string baseDir)
		{
			ignoreFiles = regexifyGlobs(ignoreFiles);
			List<string> dirsToDelete = new List<string>();
			logger.Debug("Loading directories . . .");
			var dirs = Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories);
			Console.WriteLine("{0} directories found.", dirs.Count());
			foreach (string dir in dirs)
			{
				logger.Debug("Processing directory '{0}' . . .", dir);
				var files = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories);

				if (!(files.Any(f => isIgnored(f, ignoreFiles) == false)))
				{
					dirsToDelete.Add(dir);
				}
			}

			return dirsToDelete;
		}

		public static void DeleteDirs(IEnumerable<string> dirsToDelete)
		{
			foreach (string dir in dirsToDelete.OrderBy(d => d.Length).OrderBy(d => d))
			{
				if (Directory.Exists(dir))
				{
					Directory.Delete(dir, true);
				}
			}
		}

		private static bool isIgnored(string name, string[] ignore)
		{
			foreach (string i in ignore)
			{
				Regex re = new Regex(i);
				if (re.IsMatch(name))
				{
					return true;
				}
			}

			return false;
		}

		private static string[] getIgnoreFiles(string filesList)
		{
			string[] retVal = filesList.Split(',');
			retVal = regexifyGlobs(retVal);
			return retVal;
		}

		private static string[] regexifyGlobs(string[] retVal)
		{
			retVal = retVal.Select(f => f.Replace(".", "\\.").Replace("?", ".").Replace("*", ".*?")).ToArray();
			return retVal;
		}
	}
}
